import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.system.SysRemindWorkflow;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022-10-13
 * @Version 1.0
 * @Description TODO
 **/
public class WereHouse {
    private static LogTool logTool = new LogTool("/log/huangwm/model/action/ImportAssetBeforeAcion", false);

    public static void main(String[] args) throws IOException {
        String rootPath = "E:\\WEAVER9\\ecology\\";
        GCONST.setRootPath(rootPath);
        GCONST.setServerName("ecology");
        //创建工作簿
        Workbook xssfWorkbook = new XSSFWorkbook(new FileInputStream("C:\\Users\\Huangwm\\Desktop\\SW003_Model_倉庫庫存.xlsx"));
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        //获取最后一行的num，即总行数。此处从0开始计数
        int maxRow = sheet.getLastRowNum();
        List<List<String>> Excel_datas = new ArrayList<>();
        List<String> codes = new ArrayList<>();//單獨存放物料編碼
        BaseBean baseBean = new BaseBean();
        String eop_reqUrl = baseBean.getPropValue("SW003", "eop_reqUrl");
        if (eop_reqUrl.isEmpty()) {
            System.err.println("獲取SW003.peoperties中的eop_reqUrl爲空");
        }
        String eop_reqToken = baseBean.getPropValue("SW003", "eop_reqToken");
        if (eop_reqToken.isEmpty()) {
            System.err.println("獲取SW003.peoperties中的eop_reqToken爲空");
        }

        if (!(sheet.getRow(0).getCell(1) + "").equals("物料編碼")) {
            System.err.println("Excel模板格式錯誤,第二列應為物料編碼,現為[" + sheet.getRow(0).getCell(1) + "]");
        }
        if (!(sheet.getRow(0).getCell(2) + "").equals("倉庫")) {
            System.err.println( "Excel模板格式錯誤,第三列應為倉庫,現為[" + sheet.getRow(0).getCell(2) + "]");
        }
        if (!(sheet.getRow(0).getCell(3) + "").equals("庫存數量")) {
            System.err.println( "Excel模板格式錯誤,第四列應為庫存數量,現為[" + sheet.getRow(0).getCell(3) + "]");
        }
        try {
            for (int row = 1; row <= maxRow; row++) {
                List<String> data = new ArrayList<>();
                //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                int maxCel = sheet.getRow(row).getLastCellNum();
                System.err.print("--------第" + row + "行的数据如下--------");
                for (int cel = 1; cel <= 3; cel++) {
                    //第一列和第二列是編碼和倉庫 讀取是轉成字符串 第三列數量
                    if (cel == 1) {
                        sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                        if (!isBlank(sheet.getRow(row).getCell(cel) + "").isEmpty()) {
                            if(!codes.contains(sheet.getRow(row).getCell(cel).getStringCellValue())){
                                codes.add(sheet.getRow(row).getCell(cel).getStringCellValue());
                            }
                        } else {
                            System.err.println ("第" + row + "行物料編碼存在空值");
                        }
                        data.add(isBlank(sheet.getRow(row).getCell(cel).getStringCellValue() + ""));
                    }else if (cel == 3) {
                        sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                        data.add(String.valueOf(sheet.getRow(row).getCell(cel).getStringCellValue()));
                    }else {
                        sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                        data.add(isBlank(sheet.getRow(row).getCell(cel).getStringCellValue() + ""));
                    }
                }
                System.err.println(data);
                Excel_datas.add(data);
            }
            if (codes.size() > 0 && Excel_datas.size() > 0) {
                for (List<String> value : Excel_datas) {
                    String assetCode = value.get(0);//物料編碼
                    String wareHouse = value.get(1);//倉庫名稱
                    System.err.println("wareHouse="+wareHouse);
                }
                List<List<String>> newlists = new ArrayList<>();

                for(int i=0;i<codes.size();i++){
                    String code = codes.get(i);
                    List<String> newlist = new ArrayList<>();
                    newlist.add(code);
                    Double num = 0.00;
                    for(int j=0;j<Excel_datas.size();j++){
                        List<String> temp = Excel_datas.get(j);
                        String temp_code = temp.get(0);
                        Double temp_num = Double.valueOf(temp.get(2));
                        if(code.equals(temp_code)){
                            num = num+temp_num;
                        }
                    }
                    newlist.add(Double.toString(num));
                    newlists.add(newlist);
                }

                HttpRequest httpRequest = new HttpRequest();
                String times = httpRequest.getTimestamp();
                //寫入用友期初庫存
                JSONObject params_Bill = new JSONObject();
                params_Bill.put("reqNb", times);
                params_Bill.put("reqLang", "zh");
                params_Bill.put("reqToken", eop_reqToken);
                Map<String, Object> reqData_Bill = new HashMap<>();
                List<Map<String, Object>> bill = new ArrayList<>();//reqData中的bill
                Map<String, Object> bill_data = new HashMap<>();
                //billHead内容
                Map<String, Object> billHead = new HashMap<>();
                billHead.put("id",times);
                billHead.put("cbilltypecode","4A");
                billHead.put("dbilldate","2022-10-13");
                billHead.put("pk_corp","MW");
                billHead.put("vbillcode","");
                billHead.put("cdispatcherid","21");
                billHead.put("cdeptid","cdeptid");
                billHead.put("pk_calbody","MW");
                billHead.put("cwarehouseid","01");
                billHead.put("coperatorid","coperatorid");
                billHead.put("fbillflag","2");
                billHead.put("vnote","期初");
                //添加billhead内容
                bill_data.put("billHead",billHead);

                List<Map<String, Object>> billBody = new ArrayList<>();
                System.err.println(newlists);
                for (List<String> value : newlists) {
                    //如果導入數量大於0才插入
                    String assetCode = value.get(0);//物料編碼
                    Double totalquantity = Double.parseDouble(value.get(1));//总入库数量
                    if(totalquantity>0){
                        Map<String, Object> billBody_data = new HashMap<>();
                        billBody_data.put("cinventoryid",assetCode);
                        billBody_data.put("dbizdate","2022-10-13");
                        billBody_data.put("ninnum",totalquantity);
                        billBody_data.put("nprice","0");
                        billBody_data.put("nmny","0");
                        //添加body内容
                        billBody.add(billBody_data);
                    }

                }
                bill_data.put("billBody",billBody);
                bill.add(bill_data);
                reqData_Bill.put("bill",bill);
                params_Bill.put("reqData",reqData_Bill);

                System.err.println("---期初入庫傳入用友參數如下---");
                System.err.println(JSONObject.toJSONString(params_Bill));
                JSONObject json_Bill = httpRequest.CallApiPost(eop_reqUrl + "/eop/eapToUfida/icBillBegin", JSONObject.toJSONString(params_Bill));
                System.err.println("---期初入庫傳入用友結果如下---");
                System.err.println(JSONObject.toJSONString(json_Bill));
                //loggingDao.wrtieLog("0", "/eop/eapToUfida/icBillBegin", JSONObject.toJSONString(params_Bill), JSONObject.toJSONString(json_Bill));
                if(json_Bill==null || !json_Bill.getOrDefault("state","-1").equals("0")){
                    System.err.println("期初入庫失敗 " + JSONObject.toJSONString(json_Bill));
                    SysRemindWorkflow remind = new SysRemindWorkflow();
                    remind.make("EAP導入物料期初庫存對接失敗",
                            0, 0, 0, 0, 1,
                            "3",
                            "<span>EAP導入倉庫庫存&用友期初庫存入库對接失敗 " + JSONObject.toJSONString(json_Bill)
                                    + "; </span><br />详细看查看日志表uf_003_interfaceLog或当天" + "2022-10-13" + "的对接日并搜索关键字：" + times, 0);
                }

            }else{
                System.err.println ("擴展接口獲取數據爲空 ");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("導入時獲取表格數據異常 "+e.getMessage());
        }
    }
    public static String isBlank(String str) {
        if (str.isEmpty() || str.equals("null")) return "";
        return str;
    }
}
